from django.shortcuts import render, redirect
from django.http import JsonResponse
from .models import Member
from .forms import MemberForm


def member_list(request):
    members = Member.objects.filter(delflg=0)  # 查询未删除的会员
    return render(request, 'member-list.html', {'members': members})


def member_add(request):
    if request.method == 'POST':
        form = MemberForm(request.POST)
        if form.is_valid():

            form.save()
            return JsonResponse({'code': 200, 'message': '会员添加成功'})
        else:
            return JsonResponse({'code': 400, 'message': '表单数据不合法'})
    else:
        form = MemberForm()
    return render(request, 'member-add.html', {'form': form})


def member_update(request):
    if request.method == 'POST':
        mid = request.POST.get('Mid')
        member = Member.objects.get(Mid=mid)
        form = MemberForm(request.POST, instance=member)
        if form.is_valid():
            form.save()
            return JsonResponse({'code': 200, 'message': '会员信息更新成功'})
        else:
            return JsonResponse({'code': 400, 'message': '表单数据不合法'})
    else:
        return JsonResponse({'code': 400, 'message': '请求方法错误'})


def member_delete(request):
    if request.method == 'POST':
        mid = request.POST.get('Mid')
        member = Member.objects.get(Mid=mid)
        member.delflg = 1  # 标记为已删除
        member.save()
        return JsonResponse({'code': 200, 'message': '会员删除成功'})
    else:
        return JsonResponse({'code': 400, 'message': '请求方法错误'})


def member_find_by_id(request):
    mid = request.GET.get('id')
    member = Member.objects.get(Mid=mid)
    return render(request, 'member-update.html', {'member': member})
